<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="name" label="名称">
                <el-input :disabled="isDetail" v-model="form.name" placeholder="请填写客户名称"></el-input>
            </el-form-item>
            <el-form-item prop="contact" label="联系人">
                <el-input :disabled="isDetail" v-model="form.contact" placeholder="请填写联系人"></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="联系电话">
                <el-input :disabled="isDetail" v-model="form.phone" placeholder="请填写联系电话"></el-input>
            </el-form-item>
            <el-form-item prop="address" label="地址">
                <el-input :disabled="isDetail" v-model="form.address" placeholder="请填写地址"></el-input>
            </el-form-item>
            <el-form-item prop="outStart" label="期初应付">
                <el-input :disabled="isDetail" v-model="form.outStart" placeholder="请填写期初应付"></el-input>
            </el-form-item>
            <el-form-item prop="outEnd" label="期末应付">
                <el-input :disabled="true" v-model="form.outEnd" placeholder="期末应付自动生成"></el-input>
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input
                    :disabled="isDetail"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请填写备注"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button
                :disabled="isDetail"
                :loading="centerDialogLoading"
                type="primary"
                @click="handleSubmit('formRule')"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import {postApiList, putApiList} from '@/api/customer';
import getRules from '@/views/system/customer/getRules';
export default {
    name: 'center-dialog',
    props: {
        title: {
            type: String,
            default: ''
        },
        visible: {
            type: Boolean,
            default: false
        },
        dataSource: {
            type: Object,
            required: true
        }
    },
    components: {},
    data() {
        return {
            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},
            // 新建表单
            form: {
                id: undefined,
                name: '',
                contact: '',
                phone: '',
                address: '',
                outStart: '',
                outEnd: '',
                remark: ''
            },
            rules: getRules()
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        isDetail() {
            return typeof this.title === 'string' && this.title.includes('查看');
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                this.form = {
                    ...this.form,
                    ...val,
                    name: val.name,
                    contact: val.contact,
                    phone: val.phone,
                    address: val.address,
                    outStart: val.outStart,
                    outEnd: val.outEnd,
                    remark: val.remark
                };
            },
            immediate: true
        }
    },
    methods: {
        // 提交表单
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                if (valid) {
                    const form = this.form;
                    const newItem = {
                        _id: form._id,
                        name: form.name,
                        contact: form.contact,
                        phone: form.phone,
                        address: form.address,
                        outStart: form.outStart,
                        outEnd: form.outEnd,
                        remark: form.remark
                    };

                    if (this.title && this.title.includes('添加')) {
                        this.onCreate(newItem);
                    }
                    if (this.title && this.title.includes('编辑')) {
                        this.onPutData(newItem);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建角色
        onCreate(newItem) {
            this.centerDialogLoading = true;
            postApiList(newItem)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    const data = error.response && error.response.data;

                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '创建失败'});
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        onPutData(newItem) {
            this.centerDialogLoading = true;
            putApiList(newItem._id, newItem)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.form = {
                id: undefined,
                name: '',
                contact: '',
                phone: '',
                address: '',
                outStart: '',
                outEnd: '',
                remark: ''
            };
        }
    }
};
</script>
